import random

from django.shortcuts import redirect, render
from django.contrib.auth import login
from django.core.mail import send_mail
from django.conf import settings

from django.contrib.auth import authenticate
from users.models import User



def generate_code():

    """ Код для подтверждения регистрации """

    return str(random.randint(10000,99999))


def send_code_to_mail(request, email):

    """ Отправляем код на почту пользователя """

    code = generate_code()
    request.session['new_user'] = {'code': code, 'email': email}

    send_mail(
        'Подтверждение аккаунта на сайте LearnEnglish',
        f'Для подтверждения введите этот код - {code}',
        settings.EMAIL_HOST_USER,
        [settings.EMAIL_HOST_USER],
        fail_silently=False,
    )

def register_user(request, bound_form):

    """ Регистрируем пользователя """

    email, password = bound_form.cleaned_data['email'], \
                      bound_form.cleaned_data['password1']
    new_user = bound_form.save(commit=False)
    new_user.set_password(password)
    new_user.save()
    send_code_to_mail(request, email)


def check_code(request, bound_form):

    """ Проверяем введенный код пользователем """

    entered_code = bound_form.cleaned_data['code']
    generated_code, email = request.session['new_user']['code'], \
                            request.session['new_user']['email']

    if entered_code == generated_code:
        print(f'email - {email}')
        new_user = User.objects.get(email=email)
        new_user.is_active = True
        new_user.save()
        login(request, new_user)
        return redirect('account:home_page')
    else:
        bound_form.add_error('code', 'Указан неверный код')
        return render(request, 'account/entering_code.html', {'form': bound_form})


def login_user(request, bound_form):

    """ Авторизируем пользователя """

    email, password = bound_form.cleaned_data['email'], \
                      bound_form.cleaned_data['password']
    user = authenticate(email=email, password=password)

    if user is not None:
        login(request, user)
        return redirect('account:home_page')
    else:
        bound_form.add_error(None, 'Указан неверный логин и/или пароль')
        return render(request, 'registration/login.html', {'form': bound_form})
